package com.usermanage.controller;

import com.change.Enum.EnvironmentEnum;
import com.change.Service.AirSoftService;
import com.change.Service.KingDeeService;
import com.ordercore.Util.ResponseData.ResponseData;
import com.pinza.Bean.*;
import com.pinza.Common.*;
import com.usermanage.Service.ContractRealTimePriceService;
import com.usermanage.beanParam.UserBean;
import com.usermanage.util.HttpUtil;
import com.usermanage.util.JsonData;
import com.usermanage.util.StaticUtil;
import com.usermanage.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.*;
import org.json.JSONArray;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/dataCenter")
public class DataCenterController {

    @Resource
    private ContractRealTimePriceService contractRealTimePriceService;

    /**
     * 品牌列表页面
     *
     * @return
     */
    @RequestMapping("/BrandList.page")
    public ModelAndView BrandListPage() {
        ModelAndView mv = new ModelAndView();
        mv.addObject("url", StaticUtil.SKUIP);
        log.info("进入品牌列表页面");
        mv.setViewName("/dataCenter/dataDic/brandELE");
        return mv;
    }

    /**
     * 品牌列表接口
     *
     * @return
     */
    @RequestMapping("/brandList.json")
    public ResponseData BrandListJson(Integer page, Integer limit, String param) {
        ResponseData responseData = BrandIOC.brandList(page, param, limit);
        return responseData;
    }

    /**
     * 品牌列表编辑
     *
     * @return
     */
    @RequestMapping(value = "/brandEdit.json", method = RequestMethod.POST)
    public ResponseData brandEdit(BrandBean brandBean, String type) {
        ResponseData responseData = null;
        switch (type) {
            case "add":
                responseData = BrandIOC.brandAdd(brandBean);
                break;
            case "update":
                responseData = BrandIOC.brandUpdate(brandBean);
                break;
            case "cancel":
                responseData = BrandIOC.brandCancel(brandBean.getId());
                break;
            default:
                responseData.setRet(false);
                responseData.setMsg("非法的参数");
                break;
        }
        return responseData;
    }

    /**
     * 单位列表页面
     *
     * @return
     */
    @RequestMapping("/unitList.page")
    public ModelAndView unitListPage() {
        ModelAndView mv = new ModelAndView();
        mv.addObject("url", StaticUtil.SKUIP);
        mv.setViewName("/dataCenter/dataDic/unitELE");
        log.info("进入单位列表页面");
        return mv;
    }

    /**
     * 单位列表接口
     *
     * @return
     */
    @RequestMapping("/unitList.json")
    public ResponseData unitListJson(Integer page, Integer limit, String param) {
        ResponseData responseData = UnitIOC.unitList(page, param, limit);
        return responseData;
    }

    /**
     * 单位列表编辑
     *
     * @return
     */
    @RequestMapping(value = "/unitEdit.json", method = RequestMethod.POST)
    public ResponseData unitEdit(UnitBean unitBean, String type) {
        ResponseData responseData = null;
        switch (type) {
            case "add":
                responseData = UnitIOC.unitAdd(unitBean);
                break;
            case "update":
                responseData = UnitIOC.unitUpdate(unitBean);
                break;
            case "cancel":
                responseData = UnitIOC.unitCancel(unitBean.getId());
                break;
            default:
                responseData.setRet(false);
                responseData.setMsg("非法的参数");
                break;
        }
        return responseData;
    }

    /**
     * 规格列表页面
     *
     * @return
     */
    @RequestMapping("/specList.page")
    public ModelAndView specPage() {
        ModelAndView mv = new ModelAndView();
        mv.addObject("url", StaticUtil.SKUIP);
        mv.setViewName("/dataCenter/dataDic/specELE");
        log.info("进入规格列表页面");
        return mv;
    }

    /**
     * 规格列表接口
     *
     * @return
     */
    @RequestMapping("/specList.json")
    public ResponseData specListJson(Integer page, Integer limit, String param) {
        ResponseData responseData = SpecIOC.specList(page, param, limit);
        return responseData;
    }

    /**
     * 规格列表编辑
     *
     * @return
     */
    @RequestMapping(value = "/specEdit.json", method = RequestMethod.POST)
    public ResponseData specEdit(SpecBean specBean, String type) {
        ResponseData responseData = null;
        switch (type) {
            case "add":
                responseData = SpecIOC.specAdd(specBean);
                break;
            case "update":
                responseData = SpecIOC.updateSpec(specBean);
                break;
            case "cancel":
                responseData = SpecIOC.cancelSpec(specBean.getId());
                break;
            default:
                responseData.setRet(false);
                responseData.setMsg("非法的参数");
                break;
        }
        return responseData;
    }

    /**
     * SlugListBySpecId列表接口
     *
     * @return
     */
    @RequestMapping("/SlugListBySpecId.json")
    public ResponseData specListJson(Integer specId) {
        ResponseData responseData = SpecIOC.getSlugListBySpecId(specId);
        return responseData;
    }

    /**
     * sku列表页面
     *
     * @return
     */
    @RequestMapping("/skuIndex.page")
    public ModelAndView skuIndex() {
        ModelAndView mv = new ModelAndView();
        mv.addObject("url", StaticUtil.LUCENE);
        mv.setViewName("/dataCenter/sku/skuIndexELE");
        log.info("进入sku列表页面");
        return mv;
    }

    @RequestMapping("/skuList.json")
    public String skuListJson(String key, int page, int size) throws Exception {
        Map map = new HashMap();
        map.put("formId", "SKU_LIST_INFO");
        map.put("key", key);
        map.put("fields", new String[0]);
        map.put("page", page);
        map.put("size", size);
        map.put("searchSet", StaticUtil.SKUFIELDS);
        String param = StringUtil.ObjectToJson(map);
        String result = HttpUtil.sendPost(StaticUtil.LUCENE + "/query", param);
        return result;
    }

    @RequestMapping("/skuBox.page")
    public ModelAndView skuBox(String sku_code, String spu_code, String spu_name) {
        ModelAndView mv = new ModelAndView();
        ResponseData responseData = SkuIOC.skuDetail(sku_code);
        if (responseData.isRet()) {
            mv.addObject("success", "success");
            Map data = (Map) responseData.getData();
            if (StringUtils.isNotBlank(spu_name)) {
                mv.addObject("spu_name", spu_name);
            } else {
                mv.addObject("spu_name", "暂无匹配");
            }
            if (StringUtils.isNotBlank(spu_name)) {
                mv.addObject("spu_code", spu_code);
            } else {
                mv.addObject("spu_code", "暂无匹配");
            }
            mv.addObject("sku_file_name", data.get("sku_file_name"));
            mv.addObject("sku_file_path", data.get("sku_file_path"));
            mv.addObject("sku_name", data.get("sku_name"));
            mv.addObject("sku_code", data.get("sku_code"));
            mv.addObject("sku_model", data.get("sku_model"));
            mv.addObject("sku_slug_set", data.get("sku_slug_set"));
            mv.addObject("sku_unit", data.get("sku_unit"));
            mv.addObject("sku_brand", data.get("sku_brand"));
            mv.addObject("sku_content", data.get("sku_content"));
            mv.addObject("sku_pic_url", data.get("sku_pic_url"));
        } else {
            mv.addObject("success", "fail");
        }
        mv.setViewName("/index/box");
        log.info("进入sku详情页面");
        return mv;
    }

    /**
     * sku添加页面
     *
     * @return
     */
    @RequestMapping("/skuAdd.page")
    public ModelAndView skuAdd() {
        ModelAndView mv = new ModelAndView();
        mv.addObject("url", StaticUtil.SKUIP);
        mv.setViewName("/dataCenter/sku/skuAddELE");
        log.info("进入sku添加页面");
        return mv;
    }

    @RequestMapping("/skuDetail.json")
    public ResponseData skuDetail(String sku_code) {
        ResponseData responseData = SkuIOC.skuDetail(sku_code);
        return responseData;
    }

    /**
     * SKU列表编辑
     *
     * @return
     */
    @RequestMapping(value = "/skuEdit.json", method = RequestMethod.POST)
    public ResponseData skuEdit(SkuBean skuBean) {
        ResponseData responseData = null;
        switch (skuBean.getRequestType()) {
            case "add":
                responseData = SkuIOC.skuAddSave(skuBean);
                Map map = (Map) responseData.getData();
                map.put("type", "add");
                contractRealTimePriceService.syncSku(map,"add");
                break;
            case "update":
                responseData = SkuIOC.skuUpdate(skuBean);
                break;
            case "cancel":
                responseData = SkuIOC.skuCancel(skuBean.getSku_code());
                break;
            default:
                responseData.setRet(false);
                responseData.setMsg("非法的参数");
                break;
        }
        return responseData;
    }

    /**
     * spu列表页
     *
     * @return
     */
    @RequestMapping(value = {"/spuIndex.page", "/spuIndex.page/"})
    public ModelAndView spuIndex() {
        ModelAndView mv = new ModelAndView();
        mv.addObject("url", StaticUtil.SKUIP);
        mv.setViewName("/dataCenter/spu/spuIndexELE");
        log.info("进入spu列表页面");
        return mv;
    }

    /**
     * spu添加页
     *
     * @return
     */
    @RequestMapping(value = {"/spuAdd.page", "/spuAdd.page/"})
    public ModelAndView spuAdd() {
        ModelAndView mv = new ModelAndView();
        mv.addObject("url", StaticUtil.SKUIP);
        mv.setViewName("/dataCenter/spu/spuAddELE");
        log.info("进入spu添加页面");
        return mv;
    }

    /**
     * 分类管理页面
     *
     * @return
     */
    @RequestMapping("/pzCfgCataLogTree.page")
    public ModelAndView pzCfgCataLogTreePage() {
        ModelAndView mv = new ModelAndView();
        mv.addObject("url", StaticUtil.SKUIP);
        mv.setViewName("/dataCenter/category/ProductCategoriesELE");
        return mv;
    }

    /**
     * 商品分类库页面
     *
     * @return
     */
    @RequestMapping("/getAllRelate.page")
    public ModelAndView getAllRelatePage() {
        ModelAndView mv = new ModelAndView();
        mv.addObject("url", StaticUtil.SKUIP);
        log.info("进入类别页面");
        mv.setViewName("/dataCenter/category/spuRelateCatagoryELE");
        return mv;
    }


    /**
     * 非标库列表页面
     */
    @RequestMapping("/nslIndex.page")
    public ModelAndView index() {
        ModelAndView mv = new ModelAndView();
        mv.addObject("url", StaticUtil.SKUIP);
        log.info("进入非标库列表页面");
        mv.setViewName("/dataCenter/nsl/nslIndexELE");
        return mv;
    }

    /**
     * 非标库列表接口
     *
     * @return
     */
    @RequestMapping("/nslList.json")
    public ResponseData nslListJson(Integer page, Integer limit, String param) {
        ResponseData responseData = NonStandardLibraryIOC.nonStandardLibraryList(page, param, limit);
        return responseData;
    }

    @RequestMapping("/nslDetail.json")
    public ResponseData nslDetail(String sku_code) {
        ResponseData responseData = NonStandardLibraryIOC.getNonStandardLibraryDetail(sku_code);
        return responseData;
    }

    /**
     * 非标库新增
     */

    @RequestMapping("/nslAddSku.page")
    public ModelAndView addSkuPage() {
        ModelAndView mv = new ModelAndView();
        mv.addObject("url", StaticUtil.SKUIP);
        mv.setViewName("/dataCenter/nsl/nslAddELE");
        log.info("进入非标库新增");
        return mv;
    }

    /**
     * 非标库列表编辑
     *
     * @return
     */
    @RequestMapping(value = "/nslEdit.json", method = RequestMethod.POST)
    public ResponseData nslEdit(NonStandardLibraryBean nonStandardLibraryBean) {
        ResponseData responseData = null;
        switch (nonStandardLibraryBean.getRequestType()) {
            case "add":
//                responseData = NonStandardLibraryIOC.nonStandardLibraryParamObtain(nonStandardLibraryBean);
//                if(responseData.isRet()){
//                    NonStandardLibraryBean   requestNonStandardLibraryBean = (NonStandardLibraryBean) responseData.getData();
//                    Map map = StringUtil.objectToMap(requestNonStandardLibraryBean);
//                    map.put("type","add");
//                    try {
//                        JsonData kingDee = requestKingDee(map);
//                        if(kingDee.isRet()){
//                            try {
//                                JsonData airSoft = requestAirSoft(map);
//                                if(airSoft.isRet()){
                responseData = NonStandardLibraryIOC.nonStandardLibraryAddSave(nonStandardLibraryBean);
//                                    if(!responseDataSave.isRet()){
//                                        map.put("type","del");
//                                        requestKingDee(map);
//                                        requestAirSoft(map);
//                                        responseData.setRet(false);
//                                        return responseData;
//                                    }
//                                    return responseDataSave;
//                                }else{
//                                    map.put("type","del");
//                                    requestKingDee(map);
//                                    responseData.setRet(false);
//                                    return responseData;
//                                }
//                            }catch (Exception e){
//                                responseData.setRet(false);
//                                return responseData;
//                            }
//                        }else{
//                            responseData.setRet(false);
//                            return responseData;
//                        }
//                    } catch (Exception e) {
//                        responseData.setRet(false);
//                        return responseData;
//                    }
//                }
                break;
            case "cancel":
//               Map map = StringUtil.objectToMap(nonStandardLibraryBean);
//               map.put("type","cancel");
//               requestKingDee(map);
//               requestAirSoft(map);
                responseData = NonStandardLibraryIOC.nonStandardLibraryCancel(nonStandardLibraryBean.getSku_code());
                break;
            default:
                responseData.setRet(false);
                responseData.setMsg("非法的参数");
                break;
        }
        return responseData;
    }

    @RequestMapping(value = "/sku/export.json")
    public void skuExportExcel(HttpServletResponse response, String key) throws IOException, Exception {
        // 第一步，创建一个webbook，对应一个Excel文件
        HSSFWorkbook wb = new HSSFWorkbook();
        // 第二步，在webbook中添加一个sheet,对应Excel文件中的sheet
        HSSFSheet sheet = wb.createSheet("SKU报表");
        //列宽
        sheet.setColumnWidth(0, 60 * 100);
        sheet.setColumnWidth(1, 160 * 100);
        sheet.setColumnWidth(2, 30 * 100);
        sheet.setColumnWidth(3, 30 * 100);
        sheet.setColumnWidth(4, 60 * 100);
        sheet.setColumnWidth(5, 100 * 100);
        sheet.setColumnWidth(6, 40 * 100);
        sheet.setColumnWidth(7, 40 * 100);

        // 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
        HSSFRow row = sheet.createRow((int) 0);
        // 第四步，创建单元格，并设置值表头 设置表头居中
        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式
        HSSFCell cell = row.createCell(0);
        cell.setCellValue("材料编码");
        cell.setCellStyle(style);
        cell = row.createCell(1);
        cell.setCellValue("材料名称");
        cell.setCellStyle(style);
        cell = row.createCell(2);
        cell.setCellValue("单位");
        cell.setCellStyle(style);
        cell = row.createCell(3);
        cell.setCellValue("品牌");
        cell.setCellStyle(style);
        cell = row.createCell(4);
        cell.setCellValue("型号");
        cell.setCellStyle(style);
        cell = row.createCell(5);
        cell.setCellValue("规格参数");
        cell.setCellStyle(style);
        cell = row.createCell(6);
        cell.setCellValue("成本价格");
        cell.setCellStyle(style);
        cell = row.createCell(7);
        cell.setCellValue("官方价格");
        cell.setCellStyle(style);
        // 第五步，写入实体数据 实际应用中这些数据从数据库得到，

        Map map = new HashMap();
        map.put("formId", "SKU_LIST_INFO");
        map.put("fields", new String[0]);
        map.put("key", key);
        map.put("size", 0);
        map.put("page", 0);
        map.put("searchSet", StaticUtil.SKUFIELDS);
        String param = StringUtil.ObjectToJson(map);
        String result = HttpUtil.sendPost(StaticUtil.LUCENE + "/query", param);
//       if(StringUtils.isBlank(result)){
//            return JsonData.fail("网络异常，请稍后重试");
//       }
        Map resultMap = StringUtil.JsonToMap(result);
        if (Boolean.valueOf(resultMap.get("result").toString())) {
            try {
                List<Map> list = (List<Map>) resultMap.get("data");
                for (int i = 0; i < list.size(); i++) {
                    row = sheet.createRow((int) i + 1);
                    // 第四步，创建单元格，并设置值
                    row.createCell(0).setCellValue(list.get(i).get("sku_code") == null ? "" : list.get(i).get("sku_code").toString());
                    row.createCell(1).setCellValue(list.get(i).get("sku_name") == null ? "" : list.get(i).get("sku_name").toString());
                    row.createCell(2).setCellValue(list.get(i).get("sku_unit") == null ? "" : list.get(i).get("sku_unit").toString());
                    row.createCell(3).setCellValue(list.get(i).get("sku_brand") == null ? "" : list.get(i).get("sku_brand").toString());
                    row.createCell(4).setCellValue(list.get(i).get("sku_model") == null ? "" : list.get(i).get("sku_model").toString());
                    row.createCell(5).setCellValue(list.get(i).get("sku_slug_set") == null ? "" : list.get(i).get("sku_slug_set").toString());
                    row.createCell(6).setCellValue(list.get(i).get("sku_cost_price") == null ? "" : list.get(i).get("sku_cost_price").toString());
                    row.createCell(7).setCellValue(list.get(i).get("sku_official_price") == null ? "" : list.get(i).get("sku_official_price").toString());
                }
                // 第六步，将文件存到指定位置
                try {
                    String filename = "SKU报表";
                    String fileName = new String(filename.getBytes(), "iso8859-1") + ".xls";
                    response.setContentType("application/octet-stream");
                    response.setHeader("Content-disposition", "attachment;filename=" + fileName);//默认Excel名称
                    response.flushBuffer();
                    response.setCharacterEncoding("UTF-8");
                    wb.write(response.getOutputStream());
                } catch (Exception e) {
                    e.printStackTrace();
//                  return JsonData.fail("导出失败，请稍后重试");
                } finally {
                    wb.close();
                }
//              return JsonData.success();
            } catch (Exception e) {
//              return JsonData.fail("导出失败，请稍后重试");
            }
        } else {
//          return JsonData.fail("导出失败，请稍后重试");
        }
    }

    @RequestMapping(value = "/nsl/export.json")
    public void nslExportExcel(HttpServletResponse response, String key) throws IOException, Exception {
        // 第一步，创建一个webbook，对应一个Excel文件
        HSSFWorkbook wb = new HSSFWorkbook();
        // 第二步，在webbook中添加一个sheet,对应Excel文件中的sheet
        HSSFSheet sheet = wb.createSheet("非标库报表");
        //列宽
        sheet.setColumnWidth(0, 30 * 100);
        sheet.setColumnWidth(1, 60 * 100);
        sheet.setColumnWidth(2, 160 * 100);
        sheet.setColumnWidth(3, 60 * 100);
        sheet.setColumnWidth(4, 60 * 100);
        sheet.setColumnWidth(5, 160 * 100);
        sheet.setColumnWidth(6, 60 * 100);

        // 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short
        HSSFRow row = sheet.createRow((int) 0);
        // 第四步，创建单元格，并设置值表头 设置表头居中
        HSSFCellStyle style = wb.createCellStyle();
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式
        HSSFCell cell = row.createCell(0);
        cell.setCellValue("序号");
        cell.setCellStyle(style);
        cell = row.createCell(1);
        cell.setCellValue("sku编号");
        cell.setCellStyle(style);
        cell = row.createCell(2);
        cell.setCellValue("sku名称");
        cell.setCellStyle(style);
        cell = row.createCell(3);
        cell.setCellValue("单位");
        cell.setCellStyle(style);
        cell = row.createCell(4);
        cell.setCellValue("品牌");
        cell.setCellStyle(style);
        cell = row.createCell(5);
        cell.setCellValue("规格参数");
        cell.setCellStyle(style);
        cell = row.createCell(6);
        cell.setCellValue("售价");
        // 第五步，写入实体数据 实际应用中这些数据从数据库得到，

        ResponseData responseData = NonStandardLibraryIOC.nonStandardLibraryList(0, key, 0);
        if (responseData.isRet()) {
            try {
                List<Map> list = (List<Map>) responseData.getData();
                for (int i = 0; i < list.size(); i++) {
                    row = sheet.createRow((int) i + 1);
                    // 第四步，创建单元格，并设置值
                    row.createCell(0).setCellValue((i + 1));
                    row.createCell(1).setCellValue(list.get(i).get("sku_code") == null ? "" : list.get(i).get("sku_code").toString());
                    row.createCell(2).setCellValue(list.get(i).get("sku_name") == null ? "" : list.get(i).get("sku_name").toString());
                    row.createCell(3).setCellValue(list.get(i).get("sku_unit") == null ? "" : list.get(i).get("sku_unit").toString());
                    row.createCell(4).setCellValue(list.get(i).get("sku_brand") == null ? "" : list.get(i).get("sku_brand").toString());
                    row.createCell(5).setCellValue(list.get(i).get("sku_slug_set") == null ? "" : list.get(i).get("sku_slug_set").toString());
                    row.createCell(6).setCellValue(list.get(i).get("sku_price") == null ? "" : list.get(i).get("sku_price").toString());
                }
                // 第六步，将文件存到指定位置
                try {
                    String filename = "非标库报表";
                    String fileName = new String(filename.getBytes(), "iso8859-1") + ".xls";
                    response.setContentType("application/octet-stream");
                    response.setHeader("Content-disposition", "attachment;filename=" + fileName);//默认Excel名称
                    response.flushBuffer();
                    response.setCharacterEncoding("UTF-8");
                    wb.write(response.getOutputStream());
                } catch (Exception e) {
                    e.printStackTrace();
//                  return JsonData.fail("导出失败，请稍后重试");
                } finally {
                    wb.close();
                }
//              return JsonData.success();
            } catch (Exception e) {
//              return JsonData.fail("导出失败，请稍后重试");
            }
        } else {
//          return JsonData.fail("导出失败，请稍后重试");
        }
    }

//    public JsonData requestKingDee(Map map) {
//        try {
//            JsonData jsonData = KingDeeService.KingDeeSubmit(StringUtil.ObjectToJson(map), StaticUtil.environmentEnum);
//            return jsonData;
//        } catch (Exception e) {
//            log.error("金蝶同步失败：" + e.toString());
//            return JsonData.fail();
//        }
//    }
//
//    public JsonData requestAirSoft(Map map) {
//        try {
//            JsonData jsonData = AirSoftService.airSoftEdit(StringUtil.ObjectToJson(map), StaticUtil.environmentEnum);
//            return jsonData;
//        } catch (Exception e) {
//            log.error("首信同步失败：" + e.toString());
//            return JsonData.fail();
//        }
//    }
}
